package com.itheima.controller;


import com.itheima.common.R;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @email 1572178030@qq.com
 * @author:黄海宾
 * @date: 2023/2/9  14:22
 */

@RestController
@RequestMapping("/common")
public class CommonController {


    /*
    * 请求url地址：/common/upload
      请求方式：POST
      请求参数：二进制文件 【 MultipartFile  file】 name=file
    * */
    @Value("${reggie.path}")
    private String Path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {

        //创建要存储的在硬盘的位置
        File urlPath = new File(Path);
        //如果该路径不存在就创建
        if (!urlPath.exists()) {
            urlPath.mkdirs();
        }
        //从前端获得图片的名字
        String originalFilename = file.getOriginalFilename();
        //获得项目名的  .jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //随机生成名字，防止存储时重名
        String nameFile = UUID.randomUUID().toString() + suffix;
        String url = Path + nameFile;
        //将文件存储到指定的位置
        file.transferTo(new File(url));
        //上传成功，返回文件名
        return R.success(nameFile);

    }

    @GetMapping("/download")
    public void download(HttpServletResponse response, String name) throws IOException {

        //读取图片的位置，告诉了地址和图片名字
        FileInputStream fileInputStream = new FileInputStream(new File(Path, name));
        //回显给前端图片
        ServletOutputStream outputStream = response.getOutputStream();

        IOUtils.copy(fileInputStream,outputStream);
    }
}
